﻿<script setup lang="ts" name="CropperModal">
import { isFunction } from '@/utils/is'
import { dataURLtoBlob } from '@/utils/file/base64Conver'
import { uploadApi } from '@/api/upload'
const dialogVisible = ref(false)

const props = defineProps({
  src: { type: String }
})

const emit = defineEmits(['uploadSuccess'])

const handleOpenDialog = () => {
  dialogVisible.value = true
}
const handleCloseDialog = () => {
  dialogVisible.value = false
}
// 子组件将方法暴露给父组件
defineExpose({ handleOpenDialog })

const previewSource = ref(props.src || '')
let filename = ''

const handleOk = async () => {
  if (uploadApi && isFunction(uploadApi)) {
    const blob = dataURLtoBlob(previewSource.value)
    const result: any = await uploadApi({ name: 'file', file: blob, filename }, { config: { showLoading: false, mockEnable: true } })
    emit('uploadSuccess', { source: previewSource.value, data: result.data })
    handleCloseDialog()
  }
}

const fileChangeHandle = (obj) => {
  filename = obj.filename
  previewSource.value = obj.value
}
</script>

<template>
  <el-dialog v-model="dialogVisible" :title="$t('moduleTitle.moduleTitleAvatarUpload')" width="800px" append-to-body destroy-on-close>
    <CropperWrap :value="props.src" @fileChange="fileChangeHandle"></CropperWrap>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseDialog">{{ $t('buttons.buttonCancel') }}</el-button>
        <el-button type="primary" @click="handleOk">{{ $t('buttons.buttonConfirmAndUpload') }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss"></style>
